﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Net.Mail;
using System.Text;
using Microsoft.Office.Interop.Outlook;
using Exception = System.Exception;

namespace bitMail.Class
{
    internal class MailHelper
    {
        private static string kopia_ident = MailerSettings.GetCCKeyName;
        private static string ukrytaKopia_ident = MailerSettings.GetBCCKeyName;
        private readonly SqliteHelper _liteHelper;


        public Template template { get; set; }

        public MailHelper()
        {
            _liteHelper = new SqliteHelper();
        }

        public bool IsValidEmail(string emailaddress)
        {
            try
            {
                var m = new MailAddress(emailaddress);
                return true;
            }
            catch (FormatException)
            {
                return false;
            }
        }

        public void WyslijOutlookTemplate(Dictionary<string, string> slownikWartosci)
        {
            try
            {
                var oApp = new Application();
                var oMailItem = (_MailItem)oApp.CreateItem(OlItemType.olMailItem);
                char[] separators = { ' ', '\t', '\n' };
                Folder folder = oApp.Session.GetDefaultFolder(OlDefaultFolders.olFolderDrafts) as Folder;
                //MailItem otMsg = oApp.CreateItemFromTemplate(MailerSettings.GetOutlookFileName, folder) as MailItem;

                MailItem otMsg = oApp.CreateItemFromTemplate(ExternalConfigHelper.OutlookPath , folder) as MailItem;
                var TemplateText = otMsg.Body.Replace("&nbsp;", "<br/>");
                var tab = TemplateText.Split(separators);
                var email = "";
                var emailKopia = "";
                var emailUkrytaKopia = "";
                var tekstDoWyslania = new StringBuilder();
                var tematMailaDoWyslania = new StringBuilder();

                var templateBody = otMsg.Subject;
                if (templateBody != null)
                {
                    var tabTematMaila = templateBody.Split(separators);
                    foreach (var item in tabTematMaila.Where(item => item.Length > 0))
                    {
                        if (item[0] == '$')
                        {
                            foreach (var item2 in slownikWartosci.Where(item2 => item2.Key.ToLower().Trim() == item.Substring(1, item.Length - 1).ToLower().Trim()))
                            {
                                tematMailaDoWyslania.Append(" " + item2.Value + " ");
                            }
                        }
                        else
                        {
                            tematMailaDoWyslania.Append(" " + item + " ");
                        }
                    }
                }
                
                foreach (var item in tab)
                {
                    if (item.Length > 0)
                    {
                        if (item[0] == '$')
                        {
                            foreach (var item2 in slownikWartosci)
                            {
                                if (item2.Key.ToLower().Trim() == item.Substring(1, item.Length - 1).ToLower().Trim())
                                {
                                    tekstDoWyslania.Append(" " + item2.Value + " ");
                                }
                            }
                        }
                        else
                        {
                            tekstDoWyslania.Append(" " + item + " ");
                        }
                    }
                }
                foreach (var item in slownikWartosci)
                {
                    if (IsValidEmail(item.Value))
                    {
                        if (item.Key.Trim().ToLower() == kopia_ident)
                        {
                            emailKopia += item.Value + ";";
                        }
                        else if (item.Key.Trim().ToLower() == ukrytaKopia_ident)
                        {
                            emailUkrytaKopia += item.Value + ";";
                        }
                        else
                        {
                            email += item.Value + ";";
                        }
                    }
                }
                if (email.Trim().Length > 0)
                {
                    try
                    {
                        if (otMsg.Attachments != null)
                        {
                            foreach(var item in otMsg.Attachments)
                            {
                                oMailItem.Attachments.Add(item);
                            }
                                
                        }
                        oMailItem.BodyFormat = OlBodyFormat.olFormatHTML;
                        oMailItem.To = email;
                        oMailItem.CC = emailKopia;
                        oMailItem.BCC = emailUkrytaKopia;
                        oMailItem.Subject = tematMailaDoWyslania.ToString();
                        oMailItem.HTMLBody = tekstDoWyslania.ToString();
                        oMailItem.Display(true);
                        _liteHelper.SaveNewDailyEntry("Wyslano " + tekstDoWyslania + " do " + email, DateTime.Now);
                    }
                    catch
                    {
                        _liteHelper.SaveNewDailyEntry("Blad przy wysylaniu do " + email + " tekst" + tekstDoWyslania,
                            DateTime.Now);
                    }
                }
            }
            catch (Exception ex)
            {
                _liteHelper.SaveNewDailyEntry("Blad przy wyslylaniu emaila" + ex.Message, DateTime.Now);
            }
        }
    }
}